package serializable.msgpack;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.msgpack.MessagePack;
/**
 * 
 * org.msgpack
 * msgpack
 * 0.6.12
 */
public class MessagePackageDemo {
	public byte[] serialize(Object obj) throws IOException {
		MessagePack mp = new MessagePack();
		mp.register(obj.getClass());
		return mp.write(obj);
	}
	
	public <T> T deserialize(InputStream is,Class<T> cla) throws IOException {
		MessagePack mp = new MessagePack();
		mp.register(cla);
		return mp.read(is, cla);
	}
	
	
	@Test
	public void serialize() {
//		A obj = new A();
//		obj.setA("a");
		B obj = new B();
		A a = new A();
		a.setB("b");
		obj.setA(a);
		List<A> as = new ArrayList<>();
		A a2 = new A();
		a2.setA("a");
		as.add(a2);
		A a3 = new A();
		a3.setA("a");
		as.add(a3);
//		obj.setAs(as);
		
		System.out.println(obj);
		
		try {
			byte[] data = serialize(obj);
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.mp"));
			System.out.println(data.length);
			bos.write(data);
			bos.flush();
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Test
	public void deserialize() {
		try {
//			A a = deserialize(new FileInputStream("a.mp"), A.class);
			//B(as=[A(a=a, b=null), A(a=a, b=null)], a=A(a=null, b=b))
			//B(as=[A(a=a, b=null), A(a=a, b=null)], a=A(a=null, b=b))
			B a = deserialize(new FileInputStream("a.mp"), B.class);
			System.out.println(a);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
